package cn.zf233.xcloud.service.impl;

import cn.zf233.xcloud.commom.R;
import cn.zf233.xcloud.entity.User;
import cn.zf233.xcloud.service.MessageService;
import cn.zf233.xcloud.util.CommonUtil;
import cn.zf233.xcloud.util.EmailUtil;
import cn.zf233.xcloud.util.SMSUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.MessagingException;

/**
 * Created by zf233 on 2021/4/22
 * 消息服务
 */
@Service
public class MessageServiceImpl implements MessageService {

    private static final String EMAIL_TITLE = "title";
    private static final String EMAIL_NICKNAME = "nickname";
    private static final String EMAIL_CONTENT = "content";
    private static final String EMAIL_URL = "url";
    private static final String THYMELEAF_NAME = "email";

    @Resource
    private EmailUtil emailUtil;

    @Resource
    private SMSUtil smsUtil;

    @Resource
    private TemplateEngine templateEngine;

    @Override
    public R sendEmail(User user, String title, String contentOfPage, String url, Boolean isAssembleUrl) {
        if (StringUtils.isBlank(url)) {
            url = emailUtil.getContentUriPrefix();
        }
        if (isAssembleUrl) {
            url = emailUtil.getContentUriPrefix() + url;
        }
        Context context = new Context();
        context.setVariable(EMAIL_TITLE, title);
        context.setVariable(EMAIL_NICKNAME, CommonUtil.getDisplayName(user));
        context.setVariable(EMAIL_CONTENT, contentOfPage);
        context.setVariable(EMAIL_URL, url);
        String content = templateEngine.process(THYMELEAF_NAME, context);
        if (StringUtils.isBlank(user.getEmail())) {
            return R.createByErrorMessage("邮件发送失败，用户未绑定邮箱");
        }
        try {
            emailUtil.send(user.getEmail(), "XCloud 提示邮件", content);
            return R.createBySuccessMessage("邮件发送成功");
        } catch (MessagingException e) {
            e.printStackTrace();
            return R.createByErrorMessage("邮件发送失败");
        }
    }

    @Override
    public R sendSMS(String phoneNumber, String code) {
        String result = smsUtil.send(phoneNumber, code);
        if (StringUtils.isBlank(result) || !result.contains("OK")) {
            return R.createByErrorMessage("短信登陆验证码发送失败：每天只可发送10次，且一小时最多5次一分钟最多1次");
        }
        return R.createBySuccess("短信登录验证码发送成功", 180L);
    }
}
